package cn.hnzxl.autosign.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xl7@qq.com
 * @date: 2021-02-19 15:16
 * @description:
 */
@RestController
@Slf4j
public class SignController {
    @GetMapping("sign")
    public String sign() {
        return "ok";
    }
    @GetMapping("add")
    public String add(String u,String p){
        users.add(new User(u,p));
        return "ok";
    }
    @GetMapping("clear")
    public String clear(String u,String p){
        users.clear();
        return "ok";
    }
    @GetMapping("list")
    public List<User> list(){
        return users;
    }
    public static List<User> users = new ArrayList<>();
    @Scheduled(cron = "7 10 09 * * ?")
    public void signTask(){
        log.info("start task");
        users.forEach(item->sign(item.getUser(),item.getPassword()));
    }
    @GetMapping("exec")
    public String exec(){
        signTask();
        return "ok";
    }
    public void sign(String u,String p) {
        String host = "https://honeybee.mifenglai.com";
        String logRes = HttpUtil.post(host+"/honeybee/user/loginByPwd", StrUtil.format("{\"mobile\":\"{}\",\"password\":\"{}\"}", u, p));
        JSON loginJSON = JSONUtil.parse(logRes);
        if(loginJSON.getByPath("status",Integer.class)!=1){
            log.error("登录失败！！");
            return ;
        }
        String token = loginJSON.getByPath("data.token", String.class);

        String signInfo = HttpUtil.createGet(host + "/honeybee/user/signInfo").header("bees-token", token).execute().body();
        JSON signInfoJSON = JSONUtil.parse(signInfo);
        if(signInfoJSON.getByPath("status",Integer.class)!=1){
            log.error("获取信息失败！！");
            return ;
        }
        if(signInfoJSON.getByPath("data.userDeviceSignInDtoList", JSONArray.class).size()==0){
            log.error("没有购买礼包！！");
            return ;
        }
        if(signInfoJSON.getByPath("data.isSignIn",Integer.class)== 0){
            Long uoId = signInfoJSON.getByPath("data.userDeviceSignInDtoList[0].uoId",Long.class);
            String body = HttpUtil.createPost(host + "/honeybee/user/sign?uoId=" + uoId).header("bees-token", token).execute().body();
            log.info("签到成功！");
        }else{
            log.info("已签到");
        }
    }
}
